package com.cy.service;


import com.cy.bfzcommons.service.FileService;
import com.cy.bfzcommons.web.util.pojo.ImageVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    //@Value("${file.localDir}")
    private String localDir;

    //@Value("${file.urlPath}")
    private String urlPath;


    @Override
    public ImageVO upload(MultipartFile file) {

        String fileName = file.getOriginalFilename();
        fileName = fileName.toLowerCase();
        if(!fileName.matches("^.+\\.(jpg|png|gif)$")) return null;                          //校验后缀

        try {                                                                                     //二级校验
            BufferedImage read = ImageIO.read(file.getInputStream());
            int height = read.getHeight();
            int width = read.getWidth();
            if(height==0||width==0) return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        String dateDir = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
        String fileDir = localDir + dateDir;                                                    //组合文件路径
        File dirFile = new File(fileDir);
        if(!dirFile.exists()) dirFile.mkdirs();                                                 //创建文件夹


        String uuid = UUID.randomUUID().toString().replace("-", "");
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        String realFileName = uuid + fileType;
        String realFilePath = fileDir + realFileName;

        try {
            file.transferTo(new File(realFilePath));
            ImageVO imageVO = new ImageVO();
            imageVO.setFileName(realFileName)
                    .setVirtualPath(realFilePath)
                    .setUrlPath(urlPath + dateDir + realFileName);
            System.out.println(file);
            return imageVO;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
